<?php

namespace My\Controller;

use Utuo\BackgroundController;

class SiteContentController extends BackgroundController {
	
	// 栏目id
	private $catId;
	
	// 初始化
	public function _initialize() {
		$this->catId = $catId = I('cat_id', 0, 'intval');
		$this->setControllerTitle("内容管理");
		$this->setActionTitle(array(
			'index' => "内容管理",
		));
		$this->setActionNav("index");
		$this->assign('cat_id', $catId);
	}
	
	// 重置头部导航
	private function resetHeader() {
		$this->setActionNav(false)->setActionNav('list,add,recycle');
		return $this;
	}
	
	// 首页
	public function indexAction() {
		layout("SiteContent/layout");
		$data = D("ArticleCategory")->where(array('cid'=>$this->aid, 'is_deleted'=>0))->order('sort')->select();
		$articleCategoryJSON = $this->getSimpleJSON($data);
		$this->assign("articleCategoryJSON", $articleCategoryJSON);
		$this->display();
	}
	
	// 栏目文章列表
	public function listAction() {
		$this->resetHeader();
		$category = M ( "ArticleCategory" )->where ( "id=%d and cid=%d and is_deleted=0", $this->catId, $this->aid )->find ();
		if ($category ["type"] == "list") {
			$this->getContentList( $category );
		} elseif ($category ["type"] == "page") { // 单页内容修改
			$this->setActionTitle("list", "单页内容修改");
			$this->categoryModify("page");
			exit ();
		} elseif ($category ["type"] == "url") { // 外部链接修改
			$this->setActionTitle("list", "外部链接修改");
			$this->categoryModify("url");
			exit ();
		}
	}
	
	// 内容列表
	public function getContentList( $category ) {
		empty($category["content_model"]) and exit("没有设置内容的类型");
		$this->redirect("Site".$category["content_model"]."/index", array('cat_id' => $this->catId));
	}
	
	// 提交链接修改
	public function urlPostAction() {
		$this->saveCategory ( array (
				'url' => I ( "url" )
		) );
	}
	
	// 提交单页内容修改
	public function pagePostAction() {
		$this->saveCategory ( array (
				'content' => htmlspecialchars_decode ( I ( "content" ) )
		) );
	}
	
	// 栏目修改 
	public function categoryModify($action) {
		$this->setActionNav(false);
		$ArticleCategory = M("ArticleCategory")->find($this->catId);
		$this->assign ( "articleCategory", $ArticleCategory );
		$this->display ($action);
	}
	
	// 保存栏目
	private function saveCategory($data) {
		$m = M ( "ArticleCategory" );
		if (false !== $m->where ( "id=%d", $this->catId )->save ( $data )) {
			$this->ajaxSuccess ( '保存成功' );
		} else {
			$this->ajaxError ( $m->getError () );
		}
	}
}